package com.example.administrator.daydayappmarket.recommend.fragment;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.administrator.daydayappmarket.Contacts;
import com.example.administrator.daydayappmarket.R;
import com.example.administrator.daydayappmarket.recommend.adapter.RecommendMainAdapter;
import com.example.administrator.daydayappmarket.recommend.moduls.AppData;
import com.example.administrator.daydayappmarket.recommend.moduls.RecommendApps;
import com.example.administrator.daydayappmarket.recommend.moduls.RecommendFootItem;
import com.example.administrator.daydayappmarket.recommend.moduls.RecommendMainItem;
import com.example.administrator.daydayappmarket.recommend.moduls.RecommendParentItem;
import com.example.administrator.daydayappmarket.recommend.moduls.RecommendPicItem;
import com.example.administrator.daydayappmarket.recommend.moduls.RecommendTopItem;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * TODO 推荐fragment
 */
public class RecommendFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2{


    private PullToRefreshListView listView;

    private int index = 1;

    private RequestQueue requestQueue;
    private MyStringRequest stringRequest;

    private List<RecommendParentItem> parentItems;

    private RecommendMainAdapter adapter;

    public RecommendFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        parentItems = new ArrayList<>();
        adapter = new RecommendMainAdapter(parentItems,getContext());
        requestQueue = Volley.newRequestQueue(getContext());
        stringrequest();
    }

        @Override
        public void onDestroy() {
            super.onDestroy();
            requestQueue.cancelAll("recommendMain");
        }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_recommend, container, false);
        listView = (PullToRefreshListView) inflate.findViewById(R.id.fragment_recommend_pullToRefreshListView);

        RelativeLayout layout = (RelativeLayout) inflate.findViewById(R.id.fragment_recommend_RelativeLayout_empty);
        ImageView imageView = (ImageView) inflate.findViewById(R.id.fragment_recommend_empty_image);
        Glide.with(getContext()).load(R.drawable.cat_loading_transparent).into(imageView);
        listView.setEmptyView(layout);

        listView.setAdapter(adapter);

        listView.setOnRefreshListener(this);
        listView.setMode(PullToRefreshBase.Mode.BOTH);


        return inflate;
    }

    /**
     * TODO上拉刷新下拉加载更多
     * @param refreshView
     */
    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        index = 1;
        stringrequest1(refreshView);
//        refreshView.onRefreshComplete();
    }

    private void stringrequest1(final PullToRefreshBase refreshView){
        stringRequest = new MyStringRequest(Contacts.URL_RECOMMENDBASE + index,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            if(index == 1){
                                parentItems.clear();
                            }

                            for (int j = 0; j < jsonArray.length(); j++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(j);
                                String theme_type = jsonObject.getString("theme_type");
                                if(theme_type.equals("entry")){
                                    JSONArray data = jsonObject.getJSONArray("data");
                                    RecommendTopItem topItem = new RecommendTopItem();
                                    List<AppData> appses = new ArrayList<>();

                                    for (int i = 0; i < data.length(); i++) {
                                        AppData apps = new AppData();
                                        apps.jsonparse(data.getJSONObject(i));
                                        appses.add(apps);
                                    }
                                    topItem.setTheme_type(theme_type);
                                    topItem.setData(appses);
                                    parentItems.add(topItem);
                                    adapter.notifyDataSetChanged();
//                                    refreshView.onRefreshComplete();
                                }


                                else if(theme_type.equals("app_topic")){

                                    JSONObject data = jsonObject.getJSONObject("data");
                                    String topic_title = data.getString("topic_title");
                                    String title_color = data.getString("title_color");
                                    String topic_name = data.getString("topic_name");
                                    JSONArray apps = data.getJSONArray("apps");
                                    RecommendMainItem mainItem = new RecommendMainItem();
                                    List<RecommendApps> appsList = new ArrayList<>();
                                    for (int i = 0; i < apps.length(); i++) {
                                        RecommendApps apps1 = new RecommendApps();
                                        JSONObject jsonObject1 = apps.getJSONObject(i);
                                        apps1.JsonParse(jsonObject1);
                                        appsList.add(apps1);
                                    }
                                    mainItem.setTopic_name(topic_name);
                                    mainItem.setData(appsList);
                                    mainItem.setTheme_type(theme_type);
                                    mainItem.setTitle_color(title_color);
                                    mainItem.setTopic_title(topic_title);
                                    parentItems.add(mainItem);
                                    adapter.notifyDataSetChanged();
                                }
                                else if(theme_type.equals("apps")){

                                    JSONArray data = jsonObject.getJSONArray("data");
                                    RecommendFootItem footItem = new RecommendFootItem();
                                    List<RecommendApps>recommendAppses = new ArrayList<>();
                                    for (int i = 0; i < data.length(); i++) {
                                        RecommendApps apps = new RecommendApps();
                                        JSONObject jsonObject1 = data.getJSONObject(i);
                                        apps.JsonParse(jsonObject1);
                                        recommendAppses.add(apps);
                                    }
                                    footItem.setData(recommendAppses);
                                    footItem.setTheme_type(theme_type);
                                    parentItems.add(footItem);
                                    adapter.notifyDataSetChanged();
                                }
                                else if(theme_type.equals("pic_topic")){
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    RecommendPicItem picItem = new RecommendPicItem();
                                    picItem.JsonParse(data);
                                    picItem.setTheme_type(theme_type);
                                    parentItems.add(picItem);
                                    adapter.notifyDataSetChanged();
                                }

                            }

                            adapter.notifyDataSetChanged();
                            refreshView.onRefreshComplete();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //网络请求失败显示失败图片
                refreshView.onRefreshComplete();
            }
        });

        stringRequest.setTag("recommendMain");
        requestQueue.add(stringRequest);

        requestQueue.start();
    }
    private void stringrequest() {
        stringRequest = new MyStringRequest(Contacts.URL_RECOMMENDBASE + index,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            for (int j = 0; j < jsonArray.length(); j++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(j);
                                String theme_type = jsonObject.getString("theme_type");
                                if(theme_type.equals("entry")){
                                    JSONArray data = jsonObject.getJSONArray("data");
                                    RecommendTopItem topItem = new RecommendTopItem();
                                    List<AppData> appses = new ArrayList<>();
                                    for (int i = 0; i < data.length(); i++) {
                                        AppData apps = new AppData();
                                        apps.jsonparse(data.getJSONObject(i));
                                        appses.add(apps);
                                    }
                                    topItem.setTheme_type(theme_type);
                                    topItem.setData(appses);
                                    parentItems.add(topItem);
                                    adapter.notifyDataSetChanged();
                                }


                                else if(theme_type.equals("app_topic")){

                                    JSONObject data = jsonObject.getJSONObject("data");
                                    String topic_title = data.getString("topic_title");
                                    String title_color = data.getString("title_color");
                                    String topic_name = data.getString("topic_name");
                                    JSONArray apps = data.getJSONArray("apps");
                                    RecommendMainItem mainItem = new RecommendMainItem();
                                    List<RecommendApps> appsList = new ArrayList<>();
                                    for (int i = 0; i < apps.length(); i++) {
                                        RecommendApps apps1 = new RecommendApps();
                                        JSONObject jsonObject1 = apps.getJSONObject(i);
                                        apps1.JsonParse(jsonObject1);
                                        appsList.add(apps1);
                                    }
                                    mainItem.setTopic_name(topic_name);
                                    mainItem.setData(appsList);
                                    mainItem.setTheme_type(theme_type);
                                    mainItem.setTitle_color(title_color);
                                    mainItem.setTopic_title(topic_title);
                                    parentItems.add(mainItem);
                                    adapter.notifyDataSetChanged();
                                }
                                else if(theme_type.equals("apps")){

                                    JSONArray data = jsonObject.getJSONArray("data");
                                    RecommendFootItem footItem = new RecommendFootItem();
                                    List<RecommendApps>recommendAppses = new ArrayList<>();
                                    for (int i = 0; i < data.length(); i++) {
                                        RecommendApps apps = new RecommendApps();
                                        JSONObject jsonObject1 = data.getJSONObject(i);
                                        apps.JsonParse(jsonObject1);
                                        recommendAppses.add(apps);
                                    }
                                    footItem.setData(recommendAppses);
                                    footItem.setTheme_type(theme_type);
                                    parentItems.add(footItem);
                                    adapter.notifyDataSetChanged();
                                }
                                else if(theme_type.equals("pic_topic")){
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    RecommendPicItem picItem = new RecommendPicItem();
                                    picItem.JsonParse(data);
                                    picItem.setTheme_type(theme_type);
                                    parentItems.add(picItem);
                                    adapter.notifyDataSetChanged();
                                }

                            }

                            adapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //网络请求失败显示失败图片
            }
        });

        stringRequest.setTag("recommendMain");
        requestQueue.add(stringRequest);

        requestQueue.start();
    }

    //下拉重新进行网络请求  index++

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        index++;
      stringrequest1(refreshView);
        refreshView.onRefreshComplete();
    }


    class MyStringRequest extends StringRequest{

        public MyStringRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
            super(url, listener, errorListener);
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {

//            Map<String,String> handers = super.getHeaders();
            Map<String,String> handers = new HashMap<>();
            handers.put(Contacts.HEADER_KEY,Contacts.HEADER_VALUES);

            return handers;
        }
    }
}
